package com.example.yigoumall.interceptor;

import com.example.yigoumall.service.AuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class JwtInterceptor implements HandlerInterceptor {
    
    @Autowired
    private AuthService authService;
    
    // 不需要拦截的路径
    private static final String[] EXCLUDE_PATHS = {
            "/api/auth/login",
            "/api/auth/register",
            "/api/auth/validate",
            "/error"
    };
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();
        
        // 检查是否为不需要拦截的路径
        for (String path : EXCLUDE_PATHS) {
            if (requestURI.startsWith(path)) {
                return true;
            }
        }
        
        // 获取token
        String token = request.getHeader("Authorization");
        if (token == null || !token.startsWith("Bearer ")) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.getWriter().write("{\"code\":401,\"message\":\"未提供有效的token\",\"data\":null}");
            return false;
        }
        
        // 去掉 "Bearer " 前缀
        token = token.substring(7);
        
        // 验证token
        if (!authService.validateToken(token)) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.getWriter().write("{\"code\":401,\"message\":\"Token无效或已过期\",\"data\":null}");
            return false;
        }
        
        // 将用户ID和类型存入request属性，方便后续使用
        Integer userId = authService.getUserIdFromToken(token);
        Integer userType = authService.getUserTypeFromToken(token);
        request.setAttribute("userId", userId);
        request.setAttribute("userType", userType);
        
        return true;
    }
}